package org.bjf.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;


/**
 * MD5加密和验证工具类
 *
 * @author wushen
 * @date 2015-9-23
 * @since 0.0.1
 */
public class MD5Util {

    private static final Logger logger = LoggerFactory.getLogger(MD5Util.class);

    private static final String HEX_NUMS_STR = "0123456789ABCDEF";
    private static final Integer SALT_LENGTH = 12;
    private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    /**
     * 将16进制字符串转换成字节数组
     */
    private static byte[] hexStringToByte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] hexChars = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (HEX_NUMS_STR.indexOf(hexChars[pos]) << 4
                    | HEX_NUMS_STR.indexOf(hexChars[pos + 1]));
        }
        return result;
    }

    /**
     * 将指定byte数组转换成16进制字符串
     */
    private static String byteToHexString(byte[] b) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            hexString.append(hex.toUpperCase());
        }
        return hexString.toString();
    }

    /**
     * 验证字符串是否与密文相同
     *
     * @param str       需要验证的字符串
     * @param digestStr md5加密后的密文
     * @return boolean
     */
    public static boolean validDigest(String str, String digestStr) {

        boolean result = false;
        try {

            byte[] pwdInDb = hexStringToByte(digestStr);

            byte[] salt = new byte[SALT_LENGTH];

            System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH);

            MessageDigest md = MessageDigest.getInstance("MD5");

            md.update(salt);

            md.update(str.getBytes("UTF-8"));

            byte[] digest = md.digest();

            byte[] digestInDb = new byte[pwdInDb.length - SALT_LENGTH];

            System.arraycopy(pwdInDb, SALT_LENGTH, digestInDb, 0, digestInDb.length);

            result = Arrays.equals(digest, digestInDb);
        } catch (NoSuchAlgorithmException e) {
            logger.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }

        return result;
    }

    /**
     * 获得MD5加密后的密文
     *
     * @return MD5加密后的密文
     */
    public static String encode(String str) {
        String encodeStr = null;
        try {

            byte[] pwd = null;

            SecureRandom random = new SecureRandom();

            byte[] salt = new byte[SALT_LENGTH];

            random.nextBytes(salt);

            MessageDigest md = null;

            md = MessageDigest.getInstance("MD5");

            md.update(salt);

            md.update(str.getBytes("UTF-8"));

            byte[] digest = md.digest();

            pwd = new byte[digest.length + SALT_LENGTH];

            System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH);

            System.arraycopy(digest, 0, pwd, SALT_LENGTH, digest.length);

            encodeStr = byteToHexString(pwd);
        } catch (NoSuchAlgorithmException e) {
            logger.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }

        return encodeStr;
    }

    public static String encodeWithoutSalt(String str) {
        String encodeStr = null;
        try {

            MessageDigest md = null;

            md = MessageDigest.getInstance("MD5");

            md.update(str.getBytes("UTF-8"));

            byte[] digest = md.digest();

            encodeStr = byteToHexString(digest);
        } catch (NoSuchAlgorithmException e) {
            logger.error(e.getMessage(), e);
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }

        return encodeStr;
    }

    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname)) {
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            } else {
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetname)));
            }
        } catch (Exception exception) {
        }
        return resultString;
    }

    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static void main(String[] args) throws Exception {
        String str = "12345";
        System.out.println(encode(str));

        System.out.println(encodeWithoutSalt(str));
    }
}  

